<template>
  <el-card class="box-card">
    <div class="model-role">
      <el-form :inline="true" :model="dataForm" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="dataForm.username" clearable placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-input v-model="dataForm.name" clearable placeholder="真实姓名"></el-input>
        </el-form-item>
        <el-form-item><el-button @click="getDateList">查询</el-button></el-form-item>
        <el-form-item><el-button type="primary" @click="openDialog()">添加用户</el-button></el-form-item>
      </el-form>
      <el-table :data="dataList" border style="width: 100%">
        <el-table-column prop="username" label="用户名" width="180"></el-table-column>
        <el-table-column prop="name" label="真实姓名" width="180"></el-table-column>
        <el-table-column prop="roleName" label="角色" width="180"></el-table-column>
        <el-table-column prop="phone" label="电话" width="300"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[5,10,20]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total,sizes,prev,pager,next,jumper"
        style="margin-top: 30px">
      </el-pagination>
    </div>

    <el-dialog :title="dataDialogForm.id === '' ?  dialogTitle:dialogTitle='更新用户信息' " :visible.sync="dialogFormVisible" @close="closeDialog()">
      <el-form :model="dataDialogForm" :rules="rules" ref="ruleForm">
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-select v-model="dataDialogForm.role" placeholder="请选择角色" style="width: 100%">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称" :label-width="formLabelWidth" prop="username">
          <el-input v-model="dataDialogForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" :label-width="formLabelWidth" autocomplete="off" prop="password">
          <el-input type="password" v-model="dataDialogForm.password"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" :label-width="formLabelWidth">
          <el-input v-model="dataDialogForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="dataDialogForm.phone" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm()">确 定</el-button>
      </div>
    </el-dialog>

  </el-card>
</template>

<script>

export default {
  name: 'customer',
  data() {
    var checkUserNameIsExists = (rule,value,callback) => {
      if(value === ''){
        callback(new Error('请输入用户名'))
      }else{
        //调用后端接口  检查是否存在
        this.$http.get('/user/'+value).then((res)=>{
          console.log(res)
          if(res.data.code == 200){
            callback(new Error('该用户已存在'))
          } else {
            callback()
          }
        })
      }
    };
    return {
      dialogTitle: '添加用户',
      dataForm:{
        username: "",
        name: "",
      },
      ruleForm:{
        pass: '',
      },
      dataDialogForm:{
        id: '',
        role:'',
        username:'',
        password:'',
        name:'',
        phone:'',
      },
      roleList:[],
      dataList:[],
      userName: "xiaohei",
      pageIndex: 1,
      pageSize:5,
      totalPage:0,
      datalistLoading:false ,
      dialogFormVisible:false,
      dialogFormSubmitVisible:false,
      formLabelWidth: '120px',
      rules:{
        username:[{required:true ,message:'请输入用户名',trigger:'blur'},{validator:checkUserNameIsExists,trigger: 'blur'}],
        password:[{required:true ,message:'请输入密码',trigger:'blur'},
          {min:8, message: "密码至少为8位", trigger: 'blur'},//密码校验
          {pattern: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,}$/, message: '密码必须包含至少8位，且有数字、字母和特殊符号'}],
        phone:[{required:true ,message:'请输手机号',trigger:'blur'},{pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号'},]
      }
    };
  },
  methods:{
    sizeChangeHandle(val){
      this.pageSize = val;
      this.pageIndex = 1;
      this.getDateList()
    },
    currentChangeHandle(val){
      this.pageIndex = val
      this.getDateList()
    },
    getDateList(){
      // this.datalistLoading = true
      //生命params 分页查询的参数
      const params = {
        params: {
          pageIndex:this.pageIndex,
          pageSize:this.pageSize,
          username:this.dataForm.username,
          name:this.dataForm.name
        }}
      this.$http.get('/user/findByPage',params).then((res)=>{
        console.log(res)
        this.dataList = res.data.data.records
        this.totalPage = res.data.data.current
      })
    },
    handleEdit(index,item){
      //打开更新窗口
      this.dialogFormVisible = true
      this.dataDialogForm.id = item.id
      this.dataDialogForm.role = item.role
      this.dataDialogForm.username = item.username
      this.dataDialogForm.password = item.password
      this.dataDialogForm.name = item.name
      this.dataDialogForm.phone = item.phone

      console.log('item',item)
    },
    handleDelete(index, item){
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete('/user/'+item.username).then((res)=>{
          if (res.data.code == 200) {
            this.getDateList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type:'error',
              message: '删除失败!'
            })
          }
          
        })
        
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //添加用户按钮绑定的方法
    openDialog(){
      //打开窗口
      this.dialogFormVisible = true
    },
    closeDialog(){
      //关闭窗口
      //清空表单
      this.dialogFormVisible = false
      this.dialogTitle = '添加用户'
      this.dataDialogForm.id = ''
      this.dataDialogForm.role = ''
      this.dataDialogForm.username = ''
      this.dataDialogForm.password = ''
      this.dataDialogForm.name = ''
      this.dataDialogForm.phone = ''
    },
    handleConfirm() {
      // 当点击确定按钮时，访问当前对话框的标题
      const title = this.dialogTitle;
      console.log(title)

      // 根据标题执行不同的逻辑
      if (title === '添加用户') {
        this.handleSubmitFormData('ruleForm');
      } else if (title === '更新用户信息') {
        this.handleUpdateFormData('ruleForm');
      }

      // 可以在这里添加其他需要的逻辑
    },
    handleSubmitFormData(ruleForm){
      //打开窗口
      // this.dialogFormVisible = true
      this.addUser(ruleForm)
    } ,
    handleUpdateFormData(ruleForm){
      this.updateUser(ruleForm)
    },
    updateUser(ruleForm){
      this.$refs[ruleForm].validate((valid) => {
        this.$http.put('/user',this.dataDialogForm).then((res)=>{
          console.log(res)
          this.closeDialog()
          this.getDateList()
        })
      });
    },
    addUser(ruleForm){
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
            this.dialogFormSubmitVisible = true
            console.log('--------------------')
            this.$http.post('/user',this.dataDialogForm).then((res)=>{
              console.log(res)
              this.dialogFormVisible = false   //关闭窗口
              this.closeDialog()
              this.dialogFormVisible = false
              this.dialogFormSubmitVisible= false
              this.getDateList()
            })
        } else {
          return false;
        }
      });
      
    },
    getRoleList(){
      // this.datalistLoading = true
      //生命params 分页查询的参数
      const params = {
        params: {
          pageIndex:1,
          pageSize:1000,
        }}
      this.$http.get('/role/findByPage',params).then((res)=>{
        console.log(res)
        this.roleList = res.data.data.records
      })
    },
  },
  mounted() {
    this.getDateList()
    this.getRoleList()
  },
}

</script>

